package com.luoying.itew.activity;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.Observable;
import androidx.lifecycle.ViewModelProviders;

import com.luoying.itew.R;
import com.luoying.itew.common.AntaiApplication;
import com.luoying.itew.databinding.ActivityLoginBinding;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.AppUtils;
import com.luoying.itew.util.SharedUtils;
import com.luoying.itew.util.UserUtils;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * 登录界面
 */
@RuntimePermissions
public class LoginActivity extends BaseActivity<ActivityLoginBinding> implements View.OnClickListener {
    private static final String TAG = "LoginActivity";
    // 来源 0 正常启动 1 退出按钮
    private int from = 0;

    private LoginViewModel viewModel;
    private ActivityLoginBinding dataBinding;


    @Override
    protected void init() {
        super.init();
        from = this.getIntent().getIntExtra("from", 0);
        viewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        dataBinding = DataBindingUtil.setContentView(this,getLayoutResId());
        dataBinding.setViewStyle(viewModel.viewStyle);
        LoginActivityPermissionsDispatcher.needsPermissionWithPermissionCheck(this);
        viewModel.init();
        UIChang();
    }

    /**
     * UI相关操作
     */
    private void UIChang(){
        viewModel.viewStyle.getAutoLogin().addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if(viewModel.viewStyle.getAutoLogin().get())
                    viewModel.viewStyle.getSaveName().set(true);
            }
        });
        viewModel.uiChangEvent.showToast.observe(this, s -> Toast.makeText(LoginActivity.this,s,Toast.LENGTH_LONG).show());
        viewModel.uiChangEvent.showDialog.observe(this, s -> loadDialog.show());
        viewModel.uiChangEvent.dismissDialog.observe(this, o -> loadDialog.dismiss());
        viewModel.uiChangEvent.viewToActivity.observe(this,b->goMainNewActivity());
    }


    @Override
    public int getLayoutResId() {
        return R.layout.activity_login;
    }

    private void showPermissionDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("拒绝文件存储权限会导致某些功能无法正常使用");
        builder.setNegativeButton("退出", (dialog, which) -> finish());
        builder.setPositiveButton("去授权", (dialog, which) -> AppUtils.toSeting(LoginActivity.this));
        builder.setCancelable(false);
        builder.show();
    }

    /**
     * 自动登录时间
     */
    public void autoLoginActivity(){
        UserUtils.setAndroid_id(AntaiApplication.android_id);
        UserUtils.setAccess_tokem(UserManage.getInstance().getUserToekn());
        toWithActivity(MainActivity.class);
        this.finish();
    }

    /**
     * 跳转到主页
     */
    private void goMainNewActivity(){
        toWithActivity(MainActivity.class);
        this.finish();
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.btn_login){
            if(TextUtils.isEmpty(viewModel.viewStyle.getLoginName().get())||
                    TextUtils.isEmpty(viewModel.viewStyle.getLoginPwd().get())){
                Toast.makeText(LoginActivity.this,"请输入帐号或密码", Toast.LENGTH_LONG).show();
                return;
            }
            if(viewModel.viewStyle.getLoginPwd().get().length()<6){
                Toast.makeText(LoginActivity.this,"密码最少为6位", Toast.LENGTH_LONG).show();
                return;
            }
            viewModel.startLogin();
        }
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void needsPermission() {
        //判断是记住了帐号
        if(SharedUtils.isKeepAccount()){
            //是否选择了自动登录
            if(SharedUtils.isKeepPwd()&&!TextUtils.isEmpty(SharedUtils.getUserPwd())&&from==0){
                autoLoginActivity();
            }
        }
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void neverAskPermission(){
        showPermissionDialog();
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void permissionDenied(){
        showPermissionDialog();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoginActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
